package com.air.controller;

import com.air.config.AliPayConfig;
import com.air.config.Result;
import com.air.entity.Order;
import com.air.service.AliPayService;
import com.air.service.OrderService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
public class AliPayController {


    @Autowired
    AliPayService aliPayService;


    @Autowired
    OrderService orderService;

    @RequestMapping(value = "/aliPay")
    @ResponseBody
    public Object pay(@RequestParam("orderId") int orderId,@RequestParam("userId") int userId, HttpSession session) throws IOException {
        System.out.println("要支付的订单号为"+orderId);
        Object id = session.getAttribute("id");
        System.out.println("请求id"+userId);
        System.out.println("用户id为"+id);
        if (id == null){
            return Result.fail("获取失败->用户未登录");
        }
        long userIds = (long) id;
        if (userId != userIds){
            System.out.println("请求id"+userId+"  sessionId"+userIds);
            return Result.fail("获取失败->用户信息有误");
        }
        try {
            AlipayTradePagePayResponse pay = aliPayService.pay(orderId);
            if (pay == null){
                return Result.fail("获取失败->支付异常");
            }
            return pay.body;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //@ResponseBody
    @RequestMapping("/returnUrl")
    public void returnUrlMethod(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model) throws AlipayApiException, IOException {
        System.out.println("=================================同步回调=====================================");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        //验证签名（支付宝公钥）
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AliPayConfig.getOptions().alipayPublicKey, "UTF-8", "RSA2"); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易流水号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            float money = Float.parseFloat(new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8"));

            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额="+money);

            //在这里编写自己的业务代码（对数据库的操作）
            //Order order = orderService.getOrderById(Integer.parseInt(out_trade_no));
            boolean b = orderService.updateOrderById(trade_no, out_trade_no) > 0;


            response.sendRedirect("http://localhost:8181/return.html?orderId="+out_trade_no);

        }else{
            response.sendRedirect("http://localhost:8181/return.html");
        }
    }


}
